from backend.models.login import UserInformationModel, GroupModel
from django.contrib.auth.models import User
from django.contrib import auth
from backend.serializers.login_serializers import LoginSerializer, RegisterSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from ..common.common_function import get_first_error
from send.send import send_qq_message


class Login(APIView):  # 登录相关视图类
    def post(self, request):  # 用户登录，提交post数据
        context = dict()
        data = LoginSerializer(data=request.POST)
        if not data.is_valid():  # 验证有效性
            errors = data.errors
            key, value = get_first_error(errors)
            context['error'] = key + ' ' + value[0]
            context['err_code'] = 2002
        else:
            context['data'] = dict()
            data = data.data
            username = data['username']
            password = data['password']
            user = auth.authenticate(username=username, password=password)
            if user is None:
                context['data']['error'] = "用户名或密码错误"
                context['data']['result'] = False
            else:  # 验证通过
                auth.login(request, user)
                if not data['remember']:  # 如果没有勾选14天免登录
                    request.session.set_expiry(0)
                context['data']['nickname'] = request.user.get_short_name()
                context['data']['result'] = True
            context['err_code'] = 0
        return Response(context)

    def get(self, request):  # 检测用户是否登录
        context = dict()
        if not request.user.is_anonymous:
            context['err_code'] = 0
            context['data'] = dict()
            context['data']['nickname'] = request.user.get_short_name()
            context['data']['result'] = True
        else:
            context = dict()
            context['err_code'] = 0
            context['data'] = dict()
            context['data']['result'] = False
        return Response(context)


class Register(APIView):  # 注册相关视图类
    def post(self, request):
        context = dict()
        data = RegisterSerializer(data=request.POST)
        if not data.is_valid():  # 验证数据的有效性，如果无效证明绕过了前端
            context['err_code'] = 4002
            errors = data.errors
            key, value = get_first_error(errors)
            context['error'] = key + ' ' + value[0]
        else:
            data = data.data
            username = data['username']
            password = data['password']
            nickname = data['nickname']
            email = data['email']
            context['data'] = dict()
            context['data']['result'] = True
            if User.objects.filter(username=username).exists():
                context['data']['error'] = "用户名已存在"
                context['data']['result'] = False
            if context['data']['result'] and User.objects.filter(email=email).exists():
                context['data']['error'] = "邮箱已存在"
                context['data']['result'] = False
            if context['data']['result'] and User.objects.filter(first_name=nickname).exists():
                context['data']['error'] = "昵称已存在"
                context['data']['result'] = False
            if context['data']['result']:
                user = User.objects.create_user(username=username, password=password, email=email, first_name=nickname)
                information = UserInformationModel.objects.create(user=user)  # 注册一个用户就生成对应的用户信息
                information.save()
            context['err_code'] = 0
        return Response(context)


class LogOut(APIView):  # 登出
    def get(self, request):
        auth.logout(request)
        context = dict()
        context['err_code'] = 0
        context['data'] = dict()
        context['data']['result'] = True
        return Response(context)


class SendToAll(APIView):
    def post(self, request):
        context = dict()
        user = request.user
        context['err_code'] = 0
        data = request.POST
        message = data.get('message')
        if user.is_anonymous:
            context['err_code'] = 1001
            context['error'] = "您还未登录"
            return Response(context)
        if not user.is_staff:
            context['err_code'] = 3003
            context['error'] = "您无权查看此内容"
            return Response(context)
        if message is None:
            context['err_code'] = 2001
            context['error'] = "请求参数不正确"
            return Response(context)
        userlist = iter(User.objects.all())
        while True:
            try:
                user = next(userlist)
                qq = user.information.all().first().qq
                send_message = "尊敬的{},您好，您有一条站内信息请查收：\n{}".format(user.get_short_name(), message)
                send_qq_message(qq, send_message)
            except:
                break
        return Response(context)
